package com.begye.smartloan.apptest.fangkui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtFangKuiBinding
import com.begye.smartloan.apptest.fangkui.adapter.FangKuiImageAdapter
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.renzheng.dialog.DocumentSourceTypeDialogFragment
import com.begye.smartloan.apptest.renzheng.document.RenZhengDocumentCaptureActivity
import com.begye.smartloan.apptest.tool.ToastTool
import com.begye.smartloan.apptest.tool.addTouch
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

class FangKuiActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var _binding: AtFangKuiBinding
    private lateinit var _fangKuiImageAdapter: FangKuiImageAdapter

    private lateinit var _pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    private val _fangKuiViewModel by lazy {
        ViewModelProvider(this)[FangKuiViewModel::class.java]
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        // 关联布局
        _binding = AtFangKuiBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configUIState()
        configUIEvent()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun configUIState() {

        _fangKuiViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _fangKuiViewModel.onSaveFangKuiSuccessLiveData.observe(this) {
            if (it) {
                _binding.atFangKuiEdit.text = null
                _fangKuiViewModel.initImageList()
                _fangKuiImageAdapter.notifyDataSetChanged()
                ToastTool.showMsg("Success")
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun configUIEvent() {

        _binding.atFangKuiNar.initConfig(
            text = getString(R.string.fang_kui_text_1),
            textColor = "#000000",
            leftResId = R.drawable.dres_39,
            rightResId = R.drawable.dres_38
        ) {
            if (0 == it) {
                finish()
            } else if (1 == it) {
                val dialog = KeFuDialogFragment()
                dialog.showNow(supportFragmentManager, "kefu")
            }
        }

        _fangKuiViewModel.initImageList()
        _fangKuiImageAdapter =
            FangKuiImageAdapter(_fangKuiViewModel.imageList) { action, position ->
                if (action == 0) {
                    // add
                    toDocumentActivity()

                    //
                    addTouch(type = "fang_kui_add_image_click")

                } else {
                    // delete
                    _fangKuiViewModel.imageListRemove(position)
                    _fangKuiImageAdapter.notifyDataSetChanged()
                }
            }

        _binding.atFangKuiImageList.layoutManager = GridLayoutManager(this, 3)
        _binding.atFangKuiImageList.adapter = _fangKuiImageAdapter

        // 跳转相册监听
        _pickMedia =
            registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
                if (uri != null) {
                    _fangKuiViewModel.handlePhotoAlbumResult(
                        this@FangKuiActivity,
                        uri,
                        onConversionCompleted = { type, bitmap, position ->
                            updateImagePathResult(type, bitmap, position)
                        },
                        onUploadCompleted = { type, url, position ->
                            updateImageUrlResult(type, url, position)
                        })
                } else {
                    Log.d("PhotoPicker", "No media selected")
                }
            }

        _binding.atFangKuiType1.setOnClickListener {
            _fangKuiViewModel.type = "SUGGEST"

            _binding.atFangKuiType1.setBackgroundResource(R.drawable.layer_c12_000000)
            _binding.atFangKuiType2.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)
            _binding.atFangKuiType3.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)
            _binding.atFangKuiType4.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)

            _binding.atFangKuiType1.setTextColor(Color.parseColor("#BEFF6A"))
            _binding.atFangKuiType2.setTextColor(Color.parseColor("#8E9D90"))
            _binding.atFangKuiType3.setTextColor(Color.parseColor("#8E9D90"))
            _binding.atFangKuiType4.setTextColor(Color.parseColor("#8E9D90"))

            //
            addTouch(type = "fang_kui_type_suggest_click")
        }

        _binding.atFangKuiType2.setOnClickListener {
            _fangKuiViewModel.type = "BUG"

            _binding.atFangKuiType1.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)
            _binding.atFangKuiType2.setBackgroundResource(R.drawable.layer_c12_000000)
            _binding.atFangKuiType3.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)
            _binding.atFangKuiType4.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)

            _binding.atFangKuiType1.setTextColor(Color.parseColor("#8E9D90"))
            _binding.atFangKuiType2.setTextColor(Color.parseColor("#BEFF6A"))
            _binding.atFangKuiType3.setTextColor(Color.parseColor("#8E9D90"))
            _binding.atFangKuiType4.setTextColor(Color.parseColor("#8E9D90"))

            //
            addTouch(type = "fang_kui_type_bug_click")
        }

        _binding.atFangKuiType3.setOnClickListener {
            _fangKuiViewModel.type = "PAYMENT"

            _binding.atFangKuiType1.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)
            _binding.atFangKuiType2.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)
            _binding.atFangKuiType3.setBackgroundResource(R.drawable.layer_c12_000000)
            _binding.atFangKuiType4.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)

            _binding.atFangKuiType1.setTextColor(Color.parseColor("#8E9D90"))
            _binding.atFangKuiType2.setTextColor(Color.parseColor("#8E9D90"))
            _binding.atFangKuiType3.setTextColor(Color.parseColor("#BEFF6A"))
            _binding.atFangKuiType4.setTextColor(Color.parseColor("#8E9D90"))

            //
            addTouch(type = "fang_kui_type_payment_click")
        }

        _binding.atFangKuiType4.setOnClickListener {
            _fangKuiViewModel.type = "OTHER"

            _binding.atFangKuiType1.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)
            _binding.atFangKuiType2.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)
            _binding.atFangKuiType3.setBackgroundResource(R.drawable.layer_c12_8e9d90_stroke)
            _binding.atFangKuiType4.setBackgroundResource(R.drawable.layer_c12_000000)

            _binding.atFangKuiType1.setTextColor(Color.parseColor("#8E9D90"))
            _binding.atFangKuiType2.setTextColor(Color.parseColor("#8E9D90"))
            _binding.atFangKuiType3.setTextColor(Color.parseColor("#8E9D90"))
            _binding.atFangKuiType4.setTextColor(Color.parseColor("#BEFF6A"))

            //
            addTouch(type = "fang_kui_type_other_click")
        }

        _binding.atFangKuiSubmit.setOnClickListener {
            val input = _binding.atFangKuiEdit.text.toString().trim()
            if (_fangKuiViewModel.canSubmit(input)) {
                _fangKuiViewModel.requestSaveFangKui(input)
            }

            //
            addTouch(type = "fang_kui_commit_click")
        }
    }


    private fun checkPermission(): Boolean {
        return EasyPermissions.hasPermissions(
            this,
            android.Manifest.permission.CAMERA
        )
    }

    private fun requestPermission() {
        EasyPermissions.requestPermissions(
            this,
            getString(R.string.disclosure_text_11),
            300,
            android.Manifest.permission.CAMERA
        )
    }

    private fun toDocumentActivity() {
        if (checkPermission()) {
            val dialog = DocumentSourceTypeDialogFragment {
                if (DocumentSourceTypeDialogFragment.TYPE_TAKE_PIC == it) {
                    val intent = Intent(
                        this@FangKuiActivity,
                        RenZhengDocumentCaptureActivity::class.java
                    )
                    intent.putExtra("title", "")
                    startActivityForResult(
                        intent,
                        RenZhengDocumentCaptureActivity.REQUEST_CODE_DOCUMENT_CAPTURE
                    )

                } else if (DocumentSourceTypeDialogFragment.TYPE_PHOTO_ALBUM == it) {
                    _pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
                }
            }
            dialog.showNow(supportFragmentManager, "document")

        } else {
            requestPermission()
        }
    }

    /**
     * 选择图片结果回调
     * @param type 0:身份证正面，1：行驶证正反面，2：护照正面
     * @param bitmap 图片Bitmap对象
     * @param position 位置，0：第一张，1：第二张
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun updateImagePathResult(type: Int, bitmap: Bitmap?, position: Int) {
        _fangKuiImageAdapter.notifyDataSetChanged()
    }

    /**
     * 上传图片结果回调
     * @param type 0:身份证正面，1：行驶证正反面，2：护照正面
     * @param url 图片url
     * @param position 位置，0：第一张，1：第二张
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun updateImageUrlResult(type: Int, url: String?, position: Int) {
        _fangKuiImageAdapter.notifyDataSetChanged()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        requestPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            requestPermission()

        } else if (requestCode == RenZhengDocumentCaptureActivity.REQUEST_CODE_DOCUMENT_CAPTURE) {
            if (resultCode == RESULT_OK) {
                val imageOutputPath = data?.getStringExtra("path")
                // 更新页面
                _fangKuiViewModel.handleTakePictureResult(
                    result = imageOutputPath,
                    onConversionCompleted = { type, bitmap, position ->
                        updateImagePathResult(type, bitmap, position)
                    },
                    onUploadCompleted = { type, url, position ->
                        updateImageUrlResult(type, url, position)
                    })
            }
        }
    }

    override fun onResume() {
        super.onResume()
        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()
        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}